package cn.zcf.order.service.impl;

import cn.zcf.basic.service.impl.BaseServiceImpl;
import cn.zcf.basic.utils.LoginContext;
import cn.zcf.basic.utils.PageList;
import cn.zcf.order.domain.OrderPet;
import cn.zcf.order.dto.OrderPetDto;
import cn.zcf.order.mapper.OrderPetMapper;
import cn.zcf.order.query.OrderPetQuery;
import cn.zcf.order.service.IOrderPetService;
import cn.zcf.org.domain.Emp;
import cn.zcf.org.domain.Shop;
import cn.zcf.org.mapper.EmpMapper;
import cn.zcf.org.mapper.ShopMapper;
import cn.zcf.pet.domain.SearchMessage;
import cn.zcf.pet.mapper.PetMapper;
import cn.zcf.pet.mapper.SearchMessageMapper;
import cn.zcf.user.domain.Logininfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;

@Service
public class OrderPetServiceImpl extends BaseServiceImpl<OrderPet> implements IOrderPetService {
    @Autowired
    private EmpMapper empMapper;
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private OrderPetMapper orderPetMapper;
    @Autowired
    private SearchMessageMapper searchMessageMapper;
    @Autowired
    private PetMapper petMapper;

    @Override
    public PageList<OrderPet> pageQuery(OrderPetQuery query, HttpServletRequest request) {
        Logininfo logininfo = LoginContext.getLoginInfo(request);
        Emp emp = empMapper.loadByLoginInfoId(logininfo.getId());
        if(emp.getShop_id()!=null){
            Shop shop = shopMapper.loadById(emp.getShop_id());
            query.setShop_id(shop.getId());
            if(shop.getAdmin_id()!=emp.getId()){
                query.setEmp_id(emp.getId());
            }
        }
        return super.pageQuery(query);
    }

    @Override
    public void confirm(OrderPetDto dto) {
        Long orderId = dto.getId();
        Integer payType = dto.getPayType();
        BigDecimal money = dto.getMoney();
        OrderPet orderPet = orderPetMapper.loadById(orderId);
        orderPet.setPaytype(payType);
        orderPet.setPrice(money);
        orderPet.setState(1);
        orderPetMapper.update(orderPet);
        //2.修改寻主消息：state=2，note
        SearchMessage message = searchMessageMapper.loadById(orderPet.getSearch_master_msg_id());
        message.setState(2);
        message.setNote("处理完成，交易成功");
        searchMessageMapper.update(message);
    }
    @Override
    public void remove(Long id){
        OrderPet orderPet = orderPetMapper.loadById(id);
        searchMessageMapper.reject(orderPet.getSearch_master_msg_id());
        petMapper.remove(orderPet.getPet_id());
        super.remove(id);
    }
}
